﻿using AntdUI;
using BST250301TestStand.Models;
using BST250301TestStand.Models.Helpers;
using BST250301TestStand.Models.Utils;
using CsvHelper;
using HslCommunication.Secs.Types;
using HslControls;
using MathNet.Numerics;
using MathNet.Numerics.Distributions;
using MySql.Data.MySqlClient;
using Mysqlx.Crud;
using NPOI.HPSF;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using OpenTK.Audio.OpenAL;
using Org.BouncyCastle.Asn1.X509;
using ScottPlot.Colormaps;
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BST250301TestStand.Models.Utils.PLCConfig;
using static BST250301TestStand.Models.Utils.TCUConfig;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using MethodInvoker = System.Reflection.MethodInvoker;

namespace BST250301.Views
{
    public partial class ShowStatus : AntdUI.Window
    {
        private nint windowHandle;
        private ProjectItem _item;
        private ProjectItem _itemForward;
        private bool isCluMatch = false;
        private bool isGeerMatch = false;
        private bool isTemperMatch = false;
        /// <summary>
        /// 发动机PLC是否准备好
        /// </summary>
        private bool IsReady = false;
        private bool _isAuto = false;
        public bool submit;
        public static bool IsRunning;
        public static bool IsProgress;
        /// <summary>
        /// 检测各个Check状态是否全部对勾
        /// </summary>
        public static bool IsEnabled;
        //public int NVHTestID = 0;

        public static string CSVFileFullName = string.Empty;
        public static int STABLE90 = 0;
        public static int STABLE10 = 0;

        public List<string> _ListAllCloum = new List<string>();
        public List<string> _ListAllRecord = new List<string>();
        public List<RecordReport> _ListProjectRecord = new List<RecordReport>();
        public ShowDataRecord _ShowData = new ShowDataRecord();
        public static List<ShowDataRecord> _ShowList = new List<ShowDataRecord>();
        public List<CanLogEntry> _CanLogEntries = new List<CanLogEntry>();

        public ShowTCUStatusParm _dataTCU = new ShowTCUStatusParm();
        public ShowPLCStatusParm _dataPLC = new ShowPLCStatusParm();
        public ShowNVHStatusParm _dataNVH = new ShowNVHStatusParm();

        public static ShowTCUStatusParm DataTCU = new ShowTCUStatusParm();
        public static ShowPLCStatusParm DataPLC = new ShowPLCStatusParm();
        public static ShowNVHStatusParm DataNVH = new ShowNVHStatusParm();
        public static List<RecordData> DataUserList = new List<RecordData>();
        /// <summary>
        /// 存储手动输入的数据
        /// 
        /// </summary>
        public static ConcurrentDictionary<string, string> DictionaryUser = new ConcurrentDictionary<string, string>();

        public static double CF_ControlCurrent = 0;
        public static double CR_ControlCurrent = 0;
        public static double PTO_ControlCurrent = 0;

        public static double CF_Pressure = 0;
        public static double CR_Pressure = 0;
        public static double CPTO_Pressure = 0;
        Stopwatch stopwatchShow = new Stopwatch();
        //string currentArea = string.Empty;
        /// <summary>
        /// 显示状态
        /// </summary>
        /// <param name="item">项目类</param>
        /// <param name="isedit">是否编辑模式</param>
        public ShowStatus(ProjectItem item, ProjectItem forwadItem)
        {
            if (item != null)
                this._item = item;
            if (forwadItem != null)
                this._itemForward = forwadItem;
            else
                this._itemForward = new ProjectItem();
            windowHandle = this.Handle;
            InitializeComponent();
            IsEnabled = false;
            IsRunning = false;
            this.buttonClose.Enabled = false;
            this.buttonOrder.Text = this._item.OrderID.ToString();
            flowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight;
            flowLayoutPanel1.WrapContents = true;
            flowLayoutPanel1.AutoScroll = true;

            stopwatchShow.Start();

            BindEventHandler();
            InitData();
            if (Operation.ZCAN_ClearBuffer())
                this.buttonConfirm.Type = AntdUI.TTypeMini.Success;
            GenerateCheckboxMatrix(this._item.ListRecord);
            //if (item.ConfirmWay == ConfWay.自动确认)
            //    AutoOpreation(true);

        }
        /// <summary>
        /// 初始化记录项到面板
        /// </summary>
        private void GenerateCheckboxMatrix(List<RecordData> list)
        {
            foreach (RecordData record in list)
            {
                if (record != null)
                {
                    var checkbox = new System.Windows.Forms.CheckBox
                    {
                        Enabled = false,
                        Checked = true,
                        Name = $"Checkbox_{record.ID}",
                        Text = $"{record.Name}",  // 文本标签，例如 "CR 选项 1"
                        Tag = $"{record.Name}",  // 文本标签，例如 "CR 选项 1"
                        Size = new Size(300, 32),  // 固定大小
                        Margin = new Padding(5),
                    };
                    // 添加选中事件（示例：打印选中状态）
                    //checkbox.CheckedChanged += (sender, e) =>
                    //{
                    //    var cb = sender as System.Windows.Forms.CheckBox;
                    //    Console.WriteLine($"Checkbox {cb.Tag} 选中: {cb.Checked}");
                    //};
                    if (record.DataFrom == RecordFrom.USER)
                    {
                        DictionaryUser[record.ReportName] = record.ReadValue;
                    }
                    flowLayoutPanel1.Controls.Add(checkbox);
                }
            }
            flowLayoutPanel1.PerformLayout();
        }
        /// <summary>
        /// 订阅事件
        /// </summary>
        private void BindEventHandler()
        {
            PLCConfig.ShowPLCStatus += ShowPLC;
            TCUConfig.ShowTCUStatus += ShowTCU;
            NVHConfig.ShowNVHStatus += ShowNVH;

            buttonConfirm.Click += async (sender, e) => await buttonConfirm_Click();
            buttonTestStart.Click += async (sender, e) => await buttonTestStart_Click();
            buttonClose.Click += async (sender, e) => await buttonClose_Click();
            buttonCancel.Click += async (sender, e) => await buttonCancel_Click();
            buttonEndPlan.Click += async (sender, e) => await buttonEndPlan_Click();
            Load += async (sender, e) => await ShowStatus_Load();
        }
        /// <summary>
        /// 取消订阅事件
        /// </summary>
        /// <returns></returns>
        private async Task UnBindEventHandler()
        {
            stopwatchShow.Stop();

            TCUConfig.ShowTCUStatus -= ShowTCU;
            PLCConfig.ShowPLCStatus -= ShowPLC;
            NVHConfig.ShowNVHStatus -= ShowNVH;
            await Task.Delay(50);
            buttonConfirm.Click -= async (sender, e) => await buttonConfirm_Click();
            buttonConfirm.Click -= async (sender, e) => await buttonTestStart_Click();
            buttonClose.Click -= async (sender, e) => await buttonClose_Click();
            buttonCancel.Click -= async (sender, e) => await buttonCancel_Click();
            Load -= async (sender, e) => await ShowStatus_Load();
        }
        /// <summary>
        /// 初始化界面状态
        /// </summary>
        private void InitData()
        {
            selectMasterGear.Items.Clear();
            selectSlaveGear.Items.Clear();
            selectPTOGear.Items.Clear();
            selectCFState.Items.Clear();
            selectTemperatureOil.Items.Clear();
            selectCondition.Items.Clear();
            if (this._item == null)
                return;

            var ret = Enum.GetValues(typeof(GearM));
            foreach (var item in ret)
            {
                selectMasterGear.Items.Add(item);
                if (this._item.MasterGearPosition == (GearM)item)
                    selectMasterGear.SelectedIndex = (int)item;
            }
            ret = Enum.GetValues(typeof(GearS));
            foreach (var item in ret)
            {
                selectSlaveGear.Items.Add(item);
                if (this._item.SlaveGearPosition == (GearS)item)
                    selectSlaveGear.SelectedIndex = (int)item;
            }
            ret = Enum.GetValues(typeof(GearPTO));
            foreach (var item in ret)
            {
                selectPTOGear.Items.Add(item);
                if (this._item != null && this._item.PTOGearPosition == (GearPTO)item)
                    selectPTOGear.SelectedIndex = (int)item;
            }

            ret = Enum.GetValues(typeof(ClutchStatus));
            foreach (var item in ret)
            {
                selectCFState.Items.Add(item);
                selectCRState.Items.Add(item);
                selectCPTOState.Items.Add(item);


                if (this._item.CFStatus == (ClutchStatus)item)
                {
                    selectCFState.SelectedIndex = (int)item;
                    this.checkboxCF.Checked = true;
                }
                if (this._item.CRStatus == (ClutchStatus)item)
                {
                    selectCRState.SelectedIndex = (int)item;
                    this.checkboxCR.Checked = true;
                }
                if (this._item.CPTOStatus == (ClutchStatus)item)
                {
                    selectCPTOState.SelectedIndex = (int)item;
                    this.checkboxCPTO.Checked = true;
                }
            }

            this.selectAbnormal.Enabled = false;
            this.selectFrequency.Enabled = false;
            this.selectStuttering.Enabled = false;
            this.selectSmoothShifting.Enabled = false;
            this.selectOilLeak.Enabled = false;
            this.selectNoise.Enabled = false;
            this.inputNoise.Enabled = false;
            this.inputHz.Enabled = false;
            foreach (RecordData record in this._item.ListRecord)
            {
                if (record != null && record.DataFrom == RecordFrom.NVH)
                {
                    //计算挡位
                    int testid = 0;
                    if (this._item.CFStatus == ClutchStatus.吸合)
                    {
                        testid = (int)this._item.MasterGearPosition * (int)this._item.SlaveGearPosition;
                        testid = testid > 12 ? 12 : testid;
                    }
                    else if (this._item.CRStatus == ClutchStatus.吸合)
                    {
                        testid = -(int)this._item.MasterGearPosition * (int)this._item.SlaveGearPosition;
                        testid = testid < -8 ? -8 : testid;
                    }
                    this.inputNumberNVHID.Value = testid;
                    break;
                }
                else if (record != null && record.DataFrom == RecordFrom.USER)
                {
                    if (record.Name.Contains("异常"))
                    {
                        this.selectAbnormal.Enabled = true;
                    }
                    else if (record.Name.Contains("振动"))
                    {
                        this.selectFrequency.Enabled = true;
                    }
                    else if (record.Name.Contains("异响"))
                    {
                        this.selectNoise.Enabled = true;
                    }
                    else if (record.Name.Contains("漏油"))
                    {
                        this.selectOilLeak.Enabled = true;
                    }
                    else if (record.Name.Contains("换挡"))
                    {
                        this.selectSmoothShifting.Enabled = true;
                    }
                    else if (record.Name.Contains("卡顿"))
                    {
                        this.selectStuttering.Enabled = true;
                    }
                    else if (record.Name.Contains("振幅"))
                    {
                        this.inputHz.Enabled = true;
                    }
                    else if (record.Name.Contains("噪声"))
                    {
                        this.inputNoise.Enabled = true;
                    }
                }
            }
            ret = Enum.GetValues(typeof(TOil));
            foreach (var item in ret)
            {
                selectTemperatureOil.Items.Add(item);
                if (this._item.TemperatureOil == (TOil)item)
                    selectTemperatureOil.SelectedIndex = (int)item;
            }
            ret = Enum.GetValues(typeof(ConfWay));
            foreach (var item in ret)
            {
                selectCondition.Items.Add(item);
                if (this._item.ConfirmWay == (ConfWay)item)
                    selectCondition.SelectedIndex = (int)item;
            }

            inputName.Text = this._item.Name;
            inputDesc.Text = this._item.Description;
            inputSN.Text = this._item.SN;

            inputNumberTestDuration.Value = Convert.ToDecimal(this._item.TestDuration);
            inputNumberTorque.Value = Convert.ToDecimal(this._item.LoadTorque);
            inputNumberSpeed.Value = this._item.RotateSpeed.ValueStart;
            inputNumberCFSetPointCurrentStart.Value = this._item.CFSetPointCurrent.ValueStart;
            inputNumberCRSetPointCurrentStart.Value = this._item.CRSetPointCurrent.ValueStart;
            inputNumberCPTOSetPointCurrentStart.Value = this._item.CPTOSetPointCurrent.ValueStart;
            if (this._item.RotateSpeed.StepValue != 0)
                this.selectSpeed.SelectedIndex = 1;
            else
                this.selectSpeed.SelectedIndex = 0;

            if (this._item.CFSetPointCurrent.StepValue != 0)
                this.selectCFSetPointCurrent.SelectedIndex = 1;
            else
                this.selectCFSetPointCurrent.SelectedIndex = 0;
            if (this._item.CFSetPointCurrent.SPCMode == 1)
            {
                this.selectCFSetPointCurrent.SelectedIndex = 1;
            }
            else if (this._item.CFSetPointCurrent.SPCMode == 2)//脉冲方式
            {
                this.selectCFSetPointCurrent.SelectedIndex = 2;
            }
            else if (this._item.CFSetPointCurrent.SPCMode == 3)//KP方式
            {
                this.selectCFSetPointCurrent.SelectedIndex = 3;
            }

            if (this._item.CRSetPointCurrent.StepValue != 0)
                this.selectCRSetPointCurrent.SelectedIndex = 1;
            else
                this.selectCRSetPointCurrent.SelectedIndex = 0;
            if (this._item.CRSetPointCurrent.SPCMode == 1)
            {
                this.selectCRSetPointCurrent.SelectedIndex = 1;
            }
            else if (this._item.CRSetPointCurrent.SPCMode == 2)//脉冲方式
            {
                this.selectCRSetPointCurrent.SelectedIndex = 2;
            }
            else if (this._item.CRSetPointCurrent.SPCMode == 3)//kp方式
            {
                this.selectCRSetPointCurrent.SelectedIndex = 3;
            }

            if (this._item.CPTOSetPointCurrent.StepValue != 0)
                this.selectCPTOSetPointCurrent.SelectedIndex = 1;
            else
                this.selectCPTOSetPointCurrent.SelectedIndex = 0;
            if (this._item.CPTOSetPointCurrent.SPCMode == 1)
            {
                this.selectCPTOSetPointCurrent.SelectedIndex = 1;
            }
            else if (this._item.CPTOSetPointCurrent.SPCMode == 2)//脉冲方式
            {
                this.selectCPTOSetPointCurrent.SelectedIndex = 2;
            }
            else if (this._item.CPTOSetPointCurrent.SPCMode == 3)//KP方式
            {
                this.selectCPTOSetPointCurrent.SelectedIndex = 3;
            }
            //if (this._item != null)
            //{
            //    inputName.Text = this._item.Name;
            //    inputDesc.Text = this._item.Description;
            //    selectMasterGear.Text = this._item.MasterGearPosition.ToString();
            //    selectSlaveGear.Text = this._item.SlaveGearPosition.ToString();
            //    selectClutchState.Text = this._item.ClutchState.ToString();
            //    inputNumber1.Value = this._item.RotateSeeped;
            //    selectTemperatureOil.Text = this._item.TemperatureOil.ToString();
            //    selectCondition.Text = this._item.ConfirmWay == ConfWay.自动确认 ? "自动确认" : "手动确认";
            //}
            selectMasterGear.Enabled = false;
            selectSlaveGear.Enabled = false;
            selectPTOGear.Enabled = false;

            selectCFState.Enabled = false;
            selectCRState.Enabled = false;
            selectCPTOState.Enabled = false;
            selectTemperatureOil.Enabled = false;
            selectSpeed.Enabled = false;
            selectCFSetPointCurrent.Enabled = false;
            selectCRSetPointCurrent.Enabled = false;
            selectCPTOSetPointCurrent.Enabled = false;

            inputNumberTorque.Enabled = false;
            inputNumberSpeed.Enabled = false;
            inputNumberCFSetPointCurrentStart.Enabled = false;
            inputNumberCRSetPointCurrentStart.Enabled = false;
            inputNumberCPTOSetPointCurrentStart.Enabled = false;
            inputNumberNVHID.Enabled = false;

            selectCondition.Enabled = false;
            inputName.Enabled = false;
            inputDesc.Enabled = false;
            buttonTestStart.Enabled = false;
            buttonRecordData.Enabled = true;
            inputNumberTestDuration.Enabled = false;
            inputSN.Enabled = false;
        }

        private async Task buttonClose_Click()
        {
            IsRunning = false;
            //await SetLabelTxt("测试项目数据保存");
            await Task.Delay(200);
            //await SaveUSERRecordData();
            await UnBindEventHandler();
            submit = true;
            this.Dispose();
        }
        /// <summary>
        /// 保存数据库数据，加入手动输入数据到最后行
        /// </summary>
        private async Task<bool> SaveUSERRecordData(int times, int alltimes)
        {
            try
            {
                if (this._item.ListRecord == null || this._item.ListRecord.Count == 0)
                    return true;

                bool isNVH = false;
                string nvhresult = string.Empty;
                var dtdatetime = DateTime.Now;
                var ListAllRecord = new List<string>();
                foreach (var item in this._item.ListRecord)
                {
                    if (item == null)
                        continue;

                    if (item.DataFrom == RecordFrom.USER)
                    {
                        DictionaryUser[item.ReportName] = item.ReadValue;
                    }

                    if (item.DataFrom == RecordFrom.USER && item.Name.Contains("异常"))
                    {
                        item.ReadValue = this.selectAbnormal.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("振动"))
                    {
                        item.ReadValue = this.selectFrequency.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("异响"))
                    {
                        item.ReadValue = this.selectNoise.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("漏油"))
                    {
                        item.ReadValue = this.selectOilLeak.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("换挡"))
                    {
                        item.ReadValue = this.selectSmoothShifting.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("卡顿"))
                    {
                        item.ReadValue = this.selectStuttering.Text.ToString().Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("振幅"))
                    {
                        item.ReadValue = this.inputHz.Text.Trim();
                    }
                    else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("噪声"))
                    {
                        item.ReadValue = this.inputNoise.Text.Trim();
                    }
                    //上述手动结果
                    else if (item.DataFrom == RecordFrom.NVH)
                    {
                        var nvh = NVHConfig.GetSetNVHData(item.ProductSN, DateTime.Now);
                        if (nvh.SN == item.ProductSN)
                        {
                            item.ReportName = "NVH检测结果";
                            //item.ReadValue = $"总结果：{nvh.Reult}";
                            item.ReadValue = $"{nvh.Reult}";
                            nvhresult = $"NVH检测总结果：,{nvh.Reult},详细：,工况：,{nvh.TestID},CH1平均：,{nvh.CH1DBAVG},CH2平均：,{nvh.CH2DBAVG},CH3振动平均：,{nvh.CH3VibrationAVG},CH4振动平均：,{nvh.CH4VibrationAVG},CH1声压Max：,{nvh.CH1DBMax},CH1声压Max结果：,{nvh.CH1DBMaxResult},CH2声压Max：,{nvh.CH2DBMax},CH2声压Max结果：,{nvh.CH2DBMaxResult},CH3振动Max：,{nvh.CH3VibrationMax},CH3振动Max结果：,{nvh.CH3VibrationMaxResult},CH4振动Max：,{nvh.CH4VibrationMax},CH4振动Max结果：,{nvh.CH4VibrationMaxResult}";
                        }
                    }
                    //上述NVH文件结果
                    else if (item.DataFrom == RecordFrom.PC && item.AppName== "Stable90")
                    {
                       item.ReadValue = STABLE90.ToString();
                    }
                    else if (item.DataFrom == RecordFrom.PC && item.AppName == "Stable10")
                    {
                        item.ReadValue = STABLE10.ToString();
                    }
                    //上述阶跃结果
                    ListAllRecord.Add($"{item.ReportName}：,{item.ReadValue}");
                }

                //等待其他线程设置CSV文件名完成
                if (string.IsNullOrEmpty(CSVFileFullName))
                {
                    int ws = 30;
                    while (ws > 0)
                    {
                        ws--;
                        await Task.Delay(100);
                        if (!string.IsNullOrEmpty(CSVFileFullName))
                        {
                            break;
                        }
                    }
                }

                if (string.IsNullOrEmpty(CSVFileFullName))
                    CSVFileFullName = $"D:\\Record\\Temp_{this._item.SN}_{DateTime.Now.ToString("YYYY_MM_dd_HH_mm_ss")}_{times}次.csv";
                ListAllRecord.Add(nvhresult);
                var ret = CSV.SaveProductList2CSV(ListAllRecord, CSVFileFullName);

                //保存到数据库
                return ProjectRecordReport.SaveReportRecord(this._item, dtdatetime, MainWindow.userCurrent.Account, times);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存手动数据错误：{ex.Message}");
            }
            return false;
        }

        private async Task buttonCancel_Click()
        {
            IsRunning = false;
            await UnBindEventHandler();
            await Task.Delay(50);
            submit = false;
            this.Dispose();
        }
        /// <summary>
        /// 当所有Checked为true时自动确认窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkboxOil_CheckedChanged(object sender, BoolEventArgs e)
        {
            if (this.checkboxOil.Checked && this.checkboxM.Checked && this.checkboxS.Checked && this.checkboxCPTO.Checked && this.checkboxPTOGear.Checked
                && this.checkboxCR.Checked && this.checkboxCF.Checked && this.checkboxSpeed.Checked
                && this.checkboxTorque.Checked && this.checkboxCFSetPointCurrentStart.Checked
                && this.checkboxCPTOSetPointCurrentStart.Checked && this.checkboxSetCRPointCurrentStart.Checked && this.checkboxDuration.Checked && this.checkboxNVH.Checked)
            {
                if (!IsEnabled)
                {
                    IsEnabled = true;
                    //buttonTestStart.Enabled = true;
                    buttonConfirm.Enabled = false;

                    //条件达到开始测试
                    if (this.selectCondition.SelectedIndex == (int)ConfWay.自动确认)
                    {
                        //buttonTestStart.PerformClick();
                    }
                }
            }
            else
            {
                //buttonTestStart.Enabled = false;
                //buttonConfirm.Enabled = true;
            }
        }

        private void buttonRecordData_Click(object sender, EventArgs e)
        {
            ShowRecrdDataForm(false);

            //var form = new ShowRealList(this._item, Operate.antList,false);// { Size = new Size(800, 500) };
            //AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            //{
            //    BtnHeight = 0,
            //});
        }
        /// <summary>
        /// 显示记录图表
        /// </summary>
        /// <param name="seconds"></param>
        private void ShowRecrdDataForm(bool isauto)
        {

            var form = new ShowRealList(this._item, Operate.antList, isauto);// { Size = new Size(800, 500) };
            AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            {
                BtnHeight = 0,
            });
            
            //var form = new ShowReal(this._item, _ShowList, isauto, this._item.TestDuration) { Width = 1600, Height = 900 };
            //form.SetTopMost(windowHandle);
            //AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            //{
            //    BtnHeight = 0,
            //});
        }
        /// <summary>
        /// 显示PLC在线信息
        /// </summary>
        /// <param name="isconnected"></param>
        /// <param name="Remotename"></param>
        private void ShowPLC(object? sender, ShowPLCStatusParm plc)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowPLCStatusParm>(ShowPLC), sender, plc);
                return;
            }

            this._dataPLC = DataPLC = plc;


            foreach (var item in this._item.ListRecord)
            {
                if (item == null)
                    continue;
                if (item.DataFrom == RecordFrom.USER && item.Name.Contains("异常"))
                {
                    item.ReadValue = this.selectAbnormal.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("振动"))
                {
                    item.ReadValue = this.selectFrequency.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("异响"))
                {
                    item.ReadValue = this.selectNoise.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("漏油"))
                {
                    item.ReadValue = this.selectOilLeak.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("换挡"))
                {
                    item.ReadValue = this.selectSmoothShifting.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("卡顿"))
                {
                    item.ReadValue = this.selectStuttering.Text.ToString().Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("振幅"))
                {
                    item.ReadValue = this.inputHz.Text.Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.USER && item.Name.Contains("噪声"))
                {
                    item.ReadValue = this.inputNoise.Text.Trim();
                    DictionaryUser[item.ReportName] = item.ReadValue;
                }
                else if (item.DataFrom == RecordFrom.NVH)
                {
                    int segindex = this.segmentedNVHResult.SelectIndex;
                    if (segindex == 0)
                        item.ReadValue = "NG";
                    else if (segindex == 2)
                        item.ReadValue = "OK";
                    else
                        item.ReadValue = "Null";
                    //DictionaryUser[item.ReportName] = item.ReadValue;
                }

            }

            if (stopwatchShow.ElapsedMilliseconds < MainWindow.configapp.ShowListboxInterval)//未达到显示设置时长
            {
                return;
            }
            //stopwatchShow.Stop();
            stopwatchShow.Restart();

            this.listBox2.Items.Add($"驱动速度：{this._dataPLC.DriverSpeed} rpm");
            this.listBox2.Items.Add($"加载转矩：{this._dataPLC.LoadTorqut} Nm");
            this.listBox2.Items.Add($"循环油温：{this._dataPLC.OilTempar} ℃");
            this.listBox2.Items.Add($"循环油量：{this._dataPLC.OilTraffic} ml/M");
            this.listBox2.Items.Add($"---------------{DateTime.Now.ToString("HH:mm:ss.ffff")}----------------");
            this.listBox2.SelectedIndex = this.listBox2.Items.Count - 1;


            this.listBox1.Items.Add($"CF离合器电流：{this._dataTCU.CF_FBCurrent} mA");
            this.listBox1.Items.Add($"CR离合器电流：{this._dataTCU.CR_FBCurrent} mA");
            this.listBox1.Items.Add($"PTO离合器电流：{this._dataTCU.PTO_FBCurrent} mA");
            this.listBox1.Items.Add($"-----------------------------------------------------");//this.listBox1.Items.Add($"箱体油温：{this._dataTCU.TransmOilTemp} ℃");
            //this.listBox1.Items.Add($"系统压力：{this._dataTCU.SystemPressure} bar");
            this.listBox1.Items.Add($"CF离合器油压：{this._dataTCU.CF_Pressure} bar");
            this.listBox1.Items.Add($"CR离合器油压：{this._dataTCU.CR_Pressure} bar");
            this.listBox1.Items.Add($"PTO离合器油压：{this._dataTCU.CPTO_Pressure} bar");
            //this.listBox1.Items.Add($"Pump压力：{this._dataTCU.PumpPressure} bar");
            //this.listBox1.Items.Add($"Pump速度：{this._dataTCU.PumpSpeed} bar");
            this.listBox1.Items.Add($"------------------------------------------------------");
            this.listBox1.Items.Add($"变速箱输入速度：{this._dataTCU.TransmInSpeed} rpm");
            this.listBox1.Items.Add($"变速箱输出速度：{this._dataTCU.TransmOutSpeed} rpm");
            //this.listBox1.Items.Add($"PTO速度：{this._dataTCU.PTOSpeed} rpm");
            this.listBox1.Items.Add($"---------------{DateTime.Now.ToString("HH:mm:ss.ffff")}----------------");
            this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1;
            if (listBox2.Items.Count > 100)
            {
                listBox2.Items.Clear();
                checkboxSpeed.Checked = (plc.DriverSpeed >= this._item.RotateSpeed.ValueStart - 50) && (plc.DriverSpeed <= this._item.RotateSpeed.ValueStart + 50) ? true : false;
                checkboxTorque.Checked = (plc.LoadTorqut >= this._item.LoadTorque - 100) && (plc.LoadTorqut <= this._item.LoadTorque + 100) ? true : false;
            }
        }
        private void ShowTCU(object? sender, ShowTCUStatusParm tcu)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowTCUStatusParm>(ShowTCU), sender, tcu);
                return;
            }
            DataTCU = this._dataTCU = tcu;
            // checkboxOil.Checked = tcu.OilTemp == this._item.TemperatureOil ? true : false;

            CF_ControlCurrent = this._dataTCU.CF_ControlCurrent;
            CR_ControlCurrent = this._dataTCU.CR_ControlCurrent;
            PTO_ControlCurrent = this._dataTCU.PTO_ControlCurrent;

            CF_Pressure = this._dataTCU.CF_Pressure;
            CR_Pressure = this._dataTCU.CR_Pressure;
            CPTO_Pressure = this._dataTCU.CPTO_Pressure;

            //if (stopwatchShow.ElapsedMilliseconds < MainWindow.configapp.ShowListboxInterval)//未达到显示设置时长
            //{
            //    return;
            //}
            ////stopwatchShow.Stop();
            //stopwatchShow.Restart();

            //this.listBox1.Items.Add($"CF电流：{this._dataTCU.CF_FBCurrent} mA");
            //this.listBox1.Items.Add($"CR电流：{this._dataTCU.CR_FBCurrent} mA");
            //this.listBox1.Items.Add($"PTO电流：{this._dataTCU.PTO_FBCurrent} mA");
            //this.listBox1.Items.Add($"-----------------------------------------------------");//this.listBox1.Items.Add($"箱体油温：{this._dataTCU.TransmOilTemp} ℃");
            ////this.listBox1.Items.Add($"系统压力：{this._dataTCU.SystemPressure} bar");
            //this.listBox1.Items.Add($"CF压力：{this._dataTCU.CF_Pressure} bar");
            //this.listBox1.Items.Add($"CR压力：{this._dataTCU.CR_Pressure} bar");
            //this.listBox1.Items.Add($"PTO压力：{this._dataTCU.CPTO_Pressure} bar");
            ////this.listBox1.Items.Add($"Pump压力：{this._dataTCU.PumpPressure} bar");
            ////this.listBox1.Items.Add($"Pump速度：{this._dataTCU.PumpSpeed} bar");
            //this.listBox1.Items.Add($"------------------------------------------------------");
            //this.listBox1.Items.Add($"输入速度：{this._dataTCU.TransmInSpeed} rpm");
            //this.listBox1.Items.Add($"输出速度：{this._dataTCU.TransmOutSpeed} rpm");
            ////this.listBox1.Items.Add($"PTO速度：{this._dataTCU.PTOSpeed} rpm");
            //this.listBox1.Items.Add($"---------------{DateTime.Now.ToString("HH:mm:ss.ffff")}----------------");
            //this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1;
            //if (stopwatchShow.ElapsedMilliseconds < MainWindow.configapp.ShowListboxInterval)//未达到显示设置时长
            //{
            //    return;
            //}
            //stopwatchShow.Restart();

            if (listBox1.Items.Count > 100)
            {
                listBox1.Items.Clear();


                if (this._item.CFStatus == ClutchStatus.断开)
                {
                    checkboxCFSetPointCurrentStart.Checked = checkboxCF.Checked = tcu.CF_FBCurrent <= 10 ? true : false;
                }
                else if (this._item.CFStatus == ClutchStatus.吸合)
                {
                    checkboxCFSetPointCurrentStart.Checked = checkboxCF.Checked = tcu.CF_FBCurrent >= 1000 ? true : false;
                }
                else if (this._item.CFStatus == ClutchStatus.电流控制)
                {
                    checkboxCFSetPointCurrentStart.Checked = checkboxCF.Checked = tcu.CF_FBCurrent >= this._item.CFSetPointCurrent.ValueStart ? true : false;
                }

                if (this._item.CRStatus == ClutchStatus.断开)
                {
                    checkboxSetCRPointCurrentStart.Checked = checkboxCR.Checked = tcu.CR_FBCurrent <= 10 ? true : false;
                }
                else if (this._item.CRStatus == ClutchStatus.吸合)
                {
                    checkboxSetCRPointCurrentStart.Checked = checkboxCR.Checked = tcu.CR_FBCurrent >= 1000 ? true : false;
                }
                else if (this._item.CRStatus == ClutchStatus.电流控制)
                {
                    checkboxSetCRPointCurrentStart.Checked = checkboxCR.Checked = tcu.CR_FBCurrent >= this._item.CRSetPointCurrent.ValueStart ? true : false;
                }

                if (this._item.CPTOStatus == ClutchStatus.断开)
                {
                    checkboxCPTOSetPointCurrentStart.Checked = checkboxCPTO.Checked = tcu.PTO_FBCurrent <= 10 ? true : false;
                }
                else if (this._item.CPTOStatus == ClutchStatus.吸合)
                {
                    checkboxCPTOSetPointCurrentStart.Checked = checkboxCPTO.Checked = tcu.PTO_FBCurrent >= 1000 ? true : false;
                }
                else if (this._item.CPTOStatus == ClutchStatus.电流控制)
                {
                    checkboxCPTOSetPointCurrentStart.Checked = checkboxCPTO.Checked = tcu.PTO_FBCurrent >= this._item.CPTOSetPointCurrent.ValueStart ? true : false;
                }
            }
        }
        private void ShowNVH(object? sender, ShowNVHStatusParm nvh)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowNVHStatusParm>(ShowNVH), sender, nvh);
                return;
            }
            DataNVH = this._dataNVH = nvh;
            if (!string.IsNullOrEmpty(nvh.Result))
            {
                var ret = nvh.Result.Trim() == "OK" ? 2 : 0;
                this.segmentedNVHResult.BackActive = ret == 2 ? Color.DarkGreen : Color.OrangeRed;
                this.segmentedNVHResult.SelectIndex = ret;
            }
        }

        /// <summary>
        /// 设置初始油温，启动PLC，挡位提醒
        /// </summary>
        /// <returns></returns>
        private async Task<bool> SetItem()
        {
            //设置油温
            var ret = Operation.SetOilTempa(this._item.TemperatureOil);
            await SetLabelTxt($"执行设置油温命令，返回：【{ret}】");
#if DEBUG
            MessageBox.Show("调试模式，跳过手动初始化步骤");
#else
            if (ret)
            {

                //挡位提醒
                //与上项挡位不同
                if ((this._item.MasterGearPosition != this._itemForward.MasterGearPosition) || (this._item.SlaveGearPosition != this._itemForward.SlaveGearPosition) || (this._item.PTOGearPosition != this._itemForward.PTOGearPosition))
                {
                    var form = await SetDialog("当前挡位需要更换，请手动执行。\r\n换挡完成后请确认，取消退出");
                    if (!form.submit)
                        return false;
                }
                else if (this._item.IsListFirst)//当前挡位为第一个子项运行需提醒
                {
                    var form = await SetDialog("请确认初始挡位状态是否正确？\r\n\r\n完成后点击确认，取消退出");
                    if (!form.submit)
                        return false;
                }
                var ret2 = await Operation.SetGetStartSpeed(this._item.RotateSpeed);
                await SetLabelTxt($"执行设置驱动端速度，返回：【{ret2}】");
                if (ret2)
                {
                    //if (this._item.RotateSpeed.ValueStart >= MainWindow.configapp.ClutchEN_Start && this._item.RotateSpeed.ValueStart <= MainWindow.configapp.ClutchEN_End && this._dataPLC.DriverSpeed <= MainWindow.configapp.ClutchEN_End)
                    await Task.Delay(500);
                    await SetItemClutchInit(this._item);
                    //else
                    //{
                    //    var form = new ShowDialog($"当前驱动端速度【{this._dataPLC.DriverSpeed} rpm】不符合离合器动作要求。确认继续，取消退出");
                    //    AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None) { BtnHeight = 0 });
                    //    if (!form.submit)
                    //        return false;
                    //    else
                    //    {
                    //        await Task.Delay(500);
                    //        SetItemClutchInit(this._item);
                    //    }
                    //}
                    await SetLabelTxt($"执行设置离合器状态完成.");
                }
                else
                {
                    await SetDialog($"设置驱动端速度出错:超时未达到目标速度【{this._item.RotateSpeed.ValueStart}】");
                    return false;
                }
            }
            else
            {
                await SetDialog($"执行设置油温命令出错，请检查配电柜设置");
                return false;
            }
            //await Task.Delay(1000 * 1);
            //设置速度扭矩，必须满足800转
            if (this._item.LoadTorque > 0 && this._item.RotateSpeed.ValueStart >= 800 && this._dataPLC.DriverSpeed >= 750)
            {
                var ret3 = Operation.SetTorque(this._item.LoadTorque);//扭矩
                if (ret3)
                {
                    await Task.Delay(100);
                    var ret4 = Operation.PLCLoadStart(true);
                    if (!ret4)
                    {
                        await SetDialog($"设置加载端出错，请检查重试");
                        return false;
                    }
                }
                else
                {
                    await SetDialog($"设置加载端出错，请检查重试");
                    return false;
                }
            }
            else if (this._item.LoadTorque == 0)
            {
                var ret3 = Operation.SetTorque(0);//扭矩 
                if (ret3)
                {
                    await Task.Delay(100);
                    var ret4 = Operation.PLCLoadStart(false);
                    if (!ret4)
                    {
                        await SetDialog($"设置加载端0出错，请检查重试");
                        return false;
                    }
                }
                else
                {
                    await SetDialog($"设置加载端出错，请检查重试");
                    return false;
                }
            }
            else if (this._item.LoadTorque > 0)
            {
                var ret4 = Operation.PLCLoadStart(false);
                await SetDialog($"设置加载端时驱动端转速【{this._dataPLC.DriverSpeed}】未达标，请检查重试");
                return false;
            }
#endif
            return true;
        }
        private async Task<ShowDialog> SetDialog(string msg)
        {
            //this.TopMost = false;
            var form = new ShowDialog(msg);
            // Adjusted the method call to match the correct overload
            //form.SetTopMost(this.Handle);

            form.Owner = this;
            // 当主窗体被激活时，确保子窗体也被带到最前面
            form.BringToFront(); 
            form.ShowDialog(this);
            //form.TopMost = false;
            //this.TopMost = true;
            //this.Location = new Point(80, 100);
            //this.ClientSize = new Size(1219, 868);
            return form;
        }
        /// <summary>
        /// 设置项目要求离合器
        /// </summary>
        /// <param name="item"></param>
        private async Task SetItemClutchInit(ProjectItem item)
        {
            //CF离合器
            Operation.SetCFCREn(true);//使能开

            if (this._item.CFStatus == ClutchStatus.吸合 && this._item.CRStatus == ClutchStatus.断开)//互锁
            {
                Operation.SetCFCRShp(ClutcCFCR.F);//闭合F
            }
            else if (this._item.CFStatus == ClutchStatus.断开 && this._item.CRStatus == ClutchStatus.吸合)//互锁
            {
                Operation.SetCFCRShp(ClutcCFCR.R);//闭合R
            }
            else if (this._item.CFStatus == ClutchStatus.断开 && this._item.CRStatus == ClutchStatus.断开)
            {
                Operation.SetCFCRShp(ClutcCFCR.N);//空挡
            }
            //Operation.SetCFCREn(false);//关闭CF CR使能

            await Task.Delay(500);

            //CPTO离合器
            Operation.SetCPTOEn(true);//使能开          
            if (this._item.CPTOStatus == ClutchStatus.吸合)
            {
                Operation.SetCPTOOnOff(true);//闭合
            }
            else if (this._item.CPTOStatus == ClutchStatus.断开)
            {
                Operation.SetCPTOOnOff(false);
            }
            await Task.Delay(5000);
            //Operation.SetCPTOEn(false);//关闭使能
        }
        /// <summary>
        /// NVH测试开始指令发送
        /// </summary>
        /// <returns></returns>
        private async Task SetNVHTestStart(ProjectItem item)
        {
            int testid = 0;
            foreach (RecordData record in item.ListRecord)
            {
                if (record != null && record.DataFrom == RecordFrom.NVH)
                {
                    //计算挡位
                    if (item.CFStatus == ClutchStatus.吸合)
                    {
                        testid = (int)item.MasterGearPosition * (int)item.SlaveGearPosition;
                        testid = testid > 12 ? 12 : testid;
                    }
                    else if (item.CRStatus == ClutchStatus.吸合)
                    {
                        testid = -(int)item.MasterGearPosition * (int)item.SlaveGearPosition;
                        testid = testid < -8 ? -8 : testid;
                    }
                    break;
                }
            }

            if (testid != 0)
            {
                await SetLabelTxt($"发起NVH测试：{testid}");
                await Operation.SendNVHSNTest(item.SN, testid.ToString());
            }
        }
        private void SetProgress()
        {
            while (IsProgress)
            {
                Thread.Sleep(1000);
                //this.Invoke(new System.Windows.Forms.MethodInvoker(() =>
                //{
                //    this.progress1.Value += 0.005f;
                //}));
                if (!this.IsDisposed && this.IsHandleCreated)
                {
                    this.BeginInvoke((Action)(() =>
                    {
                        // 再次安全检查，并使用 BeginInvoke 确保非阻塞
                        if (!this.progress1.IsDisposed)
                        {
                            this.progress1.Value += 0.005f;
                        }
                    }));
                }
            }
        }

        /// <summary>
        /// 开始按照电流或阶跃测试
        /// </summary>
        private async Task<bool> StartItemStep()
        {
            try
            {
                if (this._item.RotateSpeed.IsStep)
                {
                    //await Operation.SetSpeed(this._item.RotateSpeed);//电磁阀初始值
                    await Operation.SetSpeed(this._item.RotateSpeed);//电磁阀初始值
                }

                bool isCF = false;
                bool isCR = false;
                if (this._item.CFStatus == ClutchStatus.电流控制 && this._item.CRSetPointCurrent.ValueStart == 0 && !this._item.CRSetPointCurrent.IsStep)
                {
                    isCR = false;
                    isCF = true;
                    Operation.SetCurrentChan(CurrentChannel.CF);

                    await Operation.SetCFCRCPTOStep(this._item.CFSetPointCurrent, "CF", this._item);//电磁阀初始值
                }
                else if (this._item.CRStatus == ClutchStatus.电流控制 && this._item.CFSetPointCurrent.ValueStart == 0 && !this._item.CFSetPointCurrent.IsStep)
                {
                    isCF = false;
                    isCR = true;
                    Operation.SetCurrentChan(CurrentChannel.CR);
                    await Operation.SetCFCRCPTOStep(this._item.CRSetPointCurrent, "CR", this._item);
                }

                //CPTO可同时与CF或CR共存电流控制，但不阶跃
                if (this._item.CPTOStatus == ClutchStatus.电流控制)
                {
                    if (isCF)
                    {
                        Operation.SetCurrentChan(CurrentChannel.CPTOCF);
                    }
                    else if (isCR)
                    {
                        Operation.SetCurrentChan(CurrentChannel.CPTOCR);
                    }
                    else
                    {
                        Operation.SetCurrentChan(CurrentChannel.CPTO);
                    }
                    await Operation.SetCFCRCPTOStep(this._item.CPTOSetPointCurrent, "CPTO", this._item);
                }

                return IsRunning;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private async Task SetLabelTxt(string text)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((Action)(() => SetLabelTxt(text).Wait()));
                return;
            }
            this.labelRunning.Text = text;
        }
        /// <summary>
        /// 自动执行项目检测
        /// </summary>
        /// <param name="isautoclose">为true自动关窗，false人为关窗</param>
        /// <returns></returns>
        private async Task AutoOpreation(bool isauto)
        {
            if (IsRunning)
                return;

            await Task.Delay(200);
            if (this._item == null)
            {
                var form = await SetDialog("无测试数据");
                return;
            }

            bool isDoneOK = false;
            await SetLabelTxt("正在执行，请等待...");

            this.buttonConfirm.Enabled = false;
            //this.buttonConfirm.Text = "正在执行，请等待...";
            this.buttonTestStart.Enabled = false;
            this.buttonCancel.Enabled = true;


            if (isauto)
            {
#if DEBUG
                MessageBox.Show("调试模式，跳过Auto SetItem初始化步骤");
#else
                IsReady = await SetItem();//执行各个检测
               
                if (!IsReady)
                {
                    //this.buttonConfirm.Text = "一键准备";
                    this.buttonClose.Enabled = false;
                    this.buttonCancel.Enabled = true;
                    //this.buttonRecordData.Enabled = false;
                    this.buttonConfirm.Enabled = true;
                    this.buttonTestStart.Enabled = true;
                    await SetLabelTxt("尚有条件未符合，请检查后再启动");
                    //var form = new ShowDialog("尚有条件未符合，请检查");// { Size = new Size(500, 350) };
                    //AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None) { BtnHeight = 0 });
                    return;
                }
#endif
            }
            //else //手动开始测试前再次确认
            if (this._item.Times < 1)
                this._item.Times = 1;//兼容前期版本设置，保证一次检测
            for (int i = 0; i < this._item.Times; i++)
            {
                this.labelTimes.Text = $"正在执行第{i + 1}次(共{this._item.Times}次)";
                await Task.Delay(500);
#if DEBUG
                MessageBox.Show("调试模式，跳过IsEnabled检查");
#else
                if (!isauto)
                {
                    if (!IsEnabled)//检查各个checked
                    {
                        var form = await SetDialog("尚有条件未符合，确认执行？");
                        if (!form.submit)
                            return;
                    }

                    if (!IsReady)
                    {
                        await SetLabelTxt("尚有条件未符合，正在执行准备工作...");
                        if (!await SetItem())
                        {
                            var form = await SetDialog("检测到未执行成功的项目，请检测PLC系统后重试");
                            this.buttonClose.Enabled = false;
                            this.buttonCancel.Enabled = true;
                            //this.buttonRecordData.Enabled = true;
                            this.buttonConfirm.Enabled = true;
                            this.buttonTestStart.Enabled = true;
                            return;
                        }
                    }
                }
#endif
                DataTCU = new ShowTCUStatusParm();
                DataPLC = new ShowPLCStatusParm();
                DataNVH = new ShowNVHStatusParm();
                CSVFileFullName = string.Empty;
                DictionaryUser = new ConcurrentDictionary<string, string>();
                _ShowList = new List<ShowDataRecord>();
                STABLE90 = 0;
                STABLE10 = 0;
                this.progress1.Value = 0.00f;
                IsRunning = true;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                this.progress1.Value = 0.1f;
                IsProgress = true;//允许进度条运行

                //Task.Run(() => { SaveDataListRecord(); });
                Task.Run(() =>
                {
                    CSVFileFullName = ProjectRecordReport.SaveDataListRecord(this._item, MainWindow.userCurrent.Account, MainWindow.configapp.RecordInterval, i + 1, this._item.Times);
                });

                await SetNVHTestStart(this._item);

                Task.Run(() => { SetProgress(); });
                //ShowRecrdDataForm();

                await SetLabelTxt("记录数据已启动,测试中...");
                //buttonTestStart.Text = "测试中...";

                //阶跃或电流测试开始
                bool ret = await StartItemStep();//将阶跃测试的稳定时间结果获取过来
                if (ret)
                {                  
                    IsProgress = false;
                    await SetLabelTxt("Step Done,测试中...");
                    while (IsRunning)
                    {
                        this.progress1.Value = 0.9f;

                        if (stopwatch.ElapsedMilliseconds > this._item.TestDuration * 1000)//达到测试时长秒数
                        {
                            break;
                        }
                        await Task.Delay(100);
                        var pro = (float)stopwatch.ElapsedMilliseconds / (float)(this._item.TestDuration * 1000);
                        if (!this.IsDisposed && this.IsHandleCreated)
                        {
                            this.BeginInvoke((Action)(() =>
                            {
                                if (!this.progress1.IsDisposed)
                                {
                                    this.progress1.Value = (float)pro;
                                }
                            }));
                        }

                    }

                    ShowReal.IsTestting = false;
                    //this.buttonTestStart.Text = "开始测试";
                    IsRunning = false;
                    await SetLabelTxt("测试完毕");
                    isDoneOK = true;
                }
                else
                {
                    await SetLabelTxt("测试项目被中止");
                    //MessageBox.Show("测试项目被中止.");
                    //this.buttonTestStart.Text = "开始测试";
                }
                stopwatch.Stop();

                IsRunning = false;
                this.progress1.Value = 1f;
                IsProgress = false;

                if (isDoneOK)
                {
                    this._item.ListShowRealData = _ShowList;
                    await SaveUSERRecordData(i + 1, this._item.Times);
                    await SetLabelTxt("测试项目数据保存");
                }
                string issave =isDoneOK ? "已" : "未";
                await SetLabelTxt($"当前项目测试结束，数据{issave}保存，请点击【确认关闭】进行下一项测试");
            }
            if (isauto && isDoneOK)
            {
                //await Task.Delay(200);
                ShowRecrdDataForm(isauto);
                await UnBindEventHandler();
                submit = true;
                this.Dispose();
            }
            else
            {
                this.buttonClose.Enabled = true;
                this.buttonCancel.Enabled = true;
                //this.buttonRecordData.Enabled = true;
                this.buttonConfirm.Enabled = true;
                this.buttonTestStart.Enabled = true;
            }
        }

        private async Task buttonConfirm_Click()
        {
            if (this._item == null)
            {
                var form = await SetDialog("无测试数据");
                return;
            }
            this.buttonConfirm.Enabled = false;
            //this.buttonConfirm.Text = "请等待...";
            //await SetLabelTxt("正在执行，请等待...");
            this.buttonTestStart.Enabled = false;

            IsReady = await SetItem();//执行各个检测

            //this.buttonConfirm.Text = "一键准备";
            this.buttonConfirm.Enabled = true;
            this.buttonTestStart.Enabled = true;
            if (!IsReady)
            {
                var form = await SetDialog("尚有条件未符合，请检查");
            }
            //ShowRecrdDataForm();//显示记录数据窗
        }
        private async Task buttonTestStart_Click()
        {
            buttonConfirm.Enabled = false;
            buttonTestStart.Enabled = false;

#if DEBUG
            MessageBox.Show("调试模式，跳过SetItem初始化步骤");
#else
            if (!IsReady)
            {
                if (!await SetItem())
                {
                    var form = await SetDialog("检测到未执行成功的项目，请检测PLC系统后重试");
                    buttonTestStart.Enabled = true;
                    return;
                }
            }
#endif
            await AutoOpreation(false);
        }

        private async Task ShowStatus_Load()
        {
            this.Location = new Point(50, 100);
            if (this._item.ConfirmWay == ConfWay.自动确认)
                await AutoOpreation(true);
        }

        private void ShowStatus_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true; // 取消关闭             
            }
        }

        private void segmentedNVHResult_SelectIndexChanged(object sender, IntEventArgs e)
        {

        }

        private async Task buttonEndPlan_Click()
        {
            var form = await SetDialog($"确认终止当前方案【{MainWindow.configapp.PlanName}】的所有测试吗？");
            if (form.submit)
            {
                IsRunning = false;
                await UnBindEventHandler();
                await Task.Delay(50);
                Operate.IsBreak = true;
                submit = false;
                this.Dispose();
            }
        }
        //**********不要双击【一键准备】【开始测试】，这两个按钮事件在上面初始化里**************
    }
}
